package com.yunxin.download.server.infra.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.format.annotation.DateTimeFormat;

import java.lang.reflect.Field;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;

/**
 * 反射工具
 *
 * @author zero°
 * @since 2023-06-15
 */
@Slf4j
public enum ReflectUtil {

    /**
     * 实例
     */
    X;

    /**
     * @param object object
     * @param propNames propNames
     * @return List<Object>
     */
    public List<Object> getFieldValues(Object object, List<String> propNames) {
        if (object == null) {
            return Collections.emptyList();
        }
        List<Object> fieldValueList = new ArrayList<>();
        try {
            for (String propName : propNames) {
                Field field = object.getClass().getDeclaredField(propName);
                Object value = field.get(object);
                if (field.getType() == Date.class && value != null) {
                    //日期格式化
                    DateTimeFormat dateTimeFormat = field.getAnnotation(DateTimeFormat.class);
                    if (dateTimeFormat != null) {
                        String pattern = dateTimeFormat.pattern();
                        Object dateValue = getDateFormat(pattern, value);
                        fieldValueList.add(dateValue);
                    } else {
                        fieldValueList.add(value);
                    }
                } else {
                    fieldValueList.add(value);
                }
            }
        } catch (Exception e) {
            log.error("获取值失败", e);
        }
        return fieldValueList;
    }

    /**
     * @param dateTimeFormatPattern dateTimeFormatPattern
     * @param date date
     * @return Object
     */
    private Object getDateFormat(String dateTimeFormatPattern, Object date) {
        try {
            //用try-catch  防止瞎填日期格式符/ 日期格式不对 等等
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat(dateTimeFormatPattern);
            return simpleDateFormat.format(date);
        } catch (Exception e) {
            log.error("时间格式化失败", e);
        }
        return date;
    }
}
